package top.chengdongqing.manage.admin.administrator;

import java.util.Date;
import java.util.Random;
import java.util.UUID;

import com.alibaba.druid.util.StringUtils;
import com.jfinal.aop.Inject;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import top.chengdongqing.common.constant.UserConstant;
import top.chengdongqing.common.kit.Fail;
import top.chengdongqing.common.kit.StringKit;
import top.chengdongqing.common.model.AdminRole;
import top.chengdongqing.common.model.AdminUserRole;
import top.chengdongqing.common.model.User;

/**
 * 管理员管理相关逻辑层
 * 
 * @author Luyao
 *
 */
public class AdministratorService {

	@Inject
	AdminUserRole dao;

	@Inject
	User userDao;

	/**
	 * 分页查询管理员
	 * 
	 * @param roleId
	 * @param keyword
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	public Page<Record> paginate(int roleId, String keyword, int pageNumber, int pageSize) {
		Kv params = Kv.by("roleId", roleId).set("keyword", keyword);
		return Db.template("admin.administrator.paginate", params).paginate(pageNumber, pageSize);
	}

	/**
	 * 新增管理员
	 * 
	 * @param phone
	 * @param roleId
	 * @return
	 */
	@SuppressWarnings("unused")
	public Ret saveAdmin(String phone, int roleId) {
		String sql = "select id from `user` where phone = ? limit 1";
		User user = userDao.findFirst(sql, phone);
		if (user!= null) {
			return Fail.setMsg("该账号已注册");
		}
		// 查询该账号是否已分配角色
		/*
		 * if(user!=null) { sql
		 * ="select id from admin_user_role where adminId = ? limit 1";
		 * if(dao.findFirst(sql, user.getId()) != null) { return
		 * Fail.setMsg("该账号已是管理员"); } }
		 */
		String sqlUserStr="SELECT id FROM  `user`  ORDER BY ID DESC  LIMIT 1";
		Integer queryId=Db.queryInt(sqlUserStr);
		Integer userId=queryId+1; //用户id
		String userSalt=StringKit.getRandomSalt(); //盐值
		String userPassword=HashKit.sha256(UserConstant.DEFAULT_PASSWORD+userSalt); //管理员登录密码=用户手机号+盐值
		//将当前管理员角色信息录入到用户表中
		User userParam=new User();
		userParam.setId(userId);
		userParam.setName("测试账号");
		userParam.setAvatarUrl(UserConstant.DEFAULT_AVATAR_Url);
		userParam.setCreateTime(new Date());
		userParam.setPhone(phone);
	    userParam.setPassword(userPassword);
		userParam.setGender(UserConstant.DEFAULT_GENDER);
		userParam.setSecurityLevel(UserConstant.DEFAULT_SECURITY_LEVEL);
		userParam.setStatus(UserConstant.DEFAULT_ACCOUNT_STATUS);
		userParam.setSalt(userSalt);
		boolean isUserInsert=userParam.save(); //判断用户是否录入
		if(!isUserInsert){
			return Fail.setMsg(Fail.Msg.SAVE_FAIL);
		}
		AdminUserRole userRole = new AdminUserRole();
		userRole.setAdminId(userId);
		userRole.setRoleId(roleId);
		return userRole.save() ? Ret.ok() : Fail.setMsg(Fail.Msg.SAVE_FAIL);
	}

	/**
	 * 更新管理员
	 * 
	 * @param id
	 * @param roleId
	 * @return
	 */
	public Ret updateAdmin(int id, int roleId) {
	    if (AdminRole.isSuperAdmin(roleId)) { return Fail.setMsg("禁止操作超级管理员"); }
		AdminUserRole userRole = new AdminUserRole();
		userRole.setId(id);
		userRole.setRoleId(roleId);
		return userRole.update() ? Ret.ok() : Fail.setMsg(Fail.Msg.UPDATE_FAIL);
	}
	
	
	/**
	 * 功能:修改管理员密码
	 * @param id 用户id
	 * @param password 用户密码
	 * @return
	 */
	public Ret updateUserPassword(int id, String password) {
		String sql="select adminId  from admin_user_role where id=? limit 1";
		AdminUserRole adminUserRole=dao.findFirst(sql, id);
		if(adminUserRole==null){
			return Fail.setMsg("修改有误,未获取到要修改的用户角色信息!");
		}
	    Integer adminId=adminUserRole.getAdminId();
	    //获取当前用户加密的盐值
		String AdminSql="SELECT salt  FROM `user` WHERE id=? limit 1";
		User user = userDao.findFirst(AdminSql, adminId);
		if(user==null){
			return Fail.setMsg("修改有误,未获取到要修改的用户信息!");
		}
		String userSalt=user.getSalt();  //获取当前用户加密的盐值
	    String updatedPassword=StringKit.generateEncryptPassword(userSalt, password);//生成加密后的密码
	    User updateUserParam=new User();
	    updateUserParam.setId(adminId);
	    updateUserParam.setPassword(updatedPassword);
		return updateUserParam.update()? Ret.ok() : Fail.setMsg(Fail.Msg.UPDATE_FAIL);
	}
	

	/**
	 * 删除管理员
	 * 
	 * @param id
	 * @return
	 */
	public Ret deleteAdmin(int id) {
		AdminUserRole userRole = dao.findById(id);
        if(AdminRole.isSuperAdmin(userRole.getRoleId())) {
        	return Fail.setMsg("禁止删除超级管理员"); 
        }
		return userRole.delete() ? Ret.ok() : Fail.setMsg(Fail.Msg.DELETE_FAIL);
	}
}
